<?php

namespace api\ygzc\controller;

use think\facade\Db;
use api\ygzc\model\UploadQiniuModel;
use app\common\Redis;
use cmf\controller\RestBaseController;

class IndexController extends RestBaseController
{
	
	//获取超市分类
	public function home()
    {
		$this->success('获取成功');
    }
	
	//获取超市分类
	public function index()
    {
		$url = 'http://ggzyjyzx.shandong.gov.cn/wssc/portalController/mallList?system=emall';
		$res = $this->get_url($url);
		$data = json_decode($res,true);
		$new_data = $this->get_child($data);
    }
	
	
	//获取商品品牌
	public function get_brand()
    {
		$cate_ids = Db::name('goods_category')->where('platformCatalogId','<>',0)->field('id,platformCatalogId')->select();
		foreach($cate_ids as $val){
			$cate_id = $val['platformCatalogId'];
			$page = 1; 
			$rows = 16;
			$url = 'http://ggzyjyzx.shandong.gov.cn/wssc/mc_goods/'.$cate_id.'_0/sparams?from=null&page='.$page.'&rows='.$rows;
			$res = $this->get_url($url);
			$data = json_decode($res,true);
			$brand_data = $data['brands'];
			if(!empty($brand_data)){
				foreach($brand_data as $v){
					$a['cate_id'] = $val['id'];
					$a['brand_name'] = $v['name'];
					$a['old_brand_id'] = $v['id'];
					$a['create_time'] = time();
					Db::name('goods_brand')->insertGetId($a);
				}
			}
		}
    }
	
	//获取商品品牌
	public function get_goods_list()
    {
		$cate_ids = Db::name('goods_category')->where('platformCatalogId','<>',0)->where('description','=','')->field('id,platformCatalogId')->select();
		foreach($cate_ids as $v){
			$cate_id = $v['platformCatalogId']; 
			$page = 1;
			$rows = 16; 
			$url = 'http://ggzyjyzx.shandong.gov.cn/wssc/mc_goods/'.$cate_id.'_0?from=null&page='.$page.'&rows='.$rows;
			$res = $this->get_url($url);
			$data = json_decode($res,true);
			$total_page = $data['page']['pages'];
			$goods_ids = [];
			for($i=1;$i<=$total_page;$i++){
				$list_url = 'http://ggzyjyzx.shandong.gov.cn/wssc/mc_goods/'.$cate_id.'_0?from=null&page='.$i.'&rows=16';
				$back_data = $this->get_url($list_url);
				$back_data = json_decode($back_data,true);
				$back_list = $back_data['page']['list'];
				foreach($back_list as $val){
					array_push($goods_ids,$val['id']);
					$str = "goods_id-".$val['id'].",platformCatalogId-".$cate_id.",page-".$i;
					file_put_contents("./logs/log",$str.PHP_EOL, FILE_APPEND);
					Db::name('goods_list')->insert([
						'cate_id' => $cate_id,
						'goods_id' => $val['id'],
						'create_time' => date('Y-m-d H:i:s',time())
					]);
					//file_put_contents('./logs/goods_id.txt', $val['id'].',', FILE_APPEND | LOCK_EX);
				}
			}
		}
		$this->success('获取成功');
    }
	
	
	//获取商品品牌
	public function get_single_goods_list()
    {

		$cate_id = 273; 
		$page = 1; 
		$rows = 16;   
		$url = 'http://ggzyjyzx.shandong.gov.cn/wssc/mc_goods/'.$cate_id.'_0?from=null&page='.$page.'&rows='.$rows;
		$res = $this->get_url($url);
		$data = json_decode($res,true);
		$total_page = $data['page']['pages'];
		$goods_ids = [];  
		for($i=2058;$i<=$total_page;$i++){
			$list_url = 'http://ggzyjyzx.shandong.gov.cn/wssc/mc_goods/'.$cate_id.'_0?from=null&page='.$i.'&rows=16';
			$back_data = $this->get_url($list_url);
			$back_data = json_decode($back_data,true);
			if(isset($back_data['page']['list'])){
				$back_list = $back_data['page']['list'];
				foreach($back_list as $val){
					array_push($goods_ids,$val['id']);
					$str = "goods_id-".$val['id'].",platformCatalogId-".$cate_id.",page-".$i;
					file_put_contents("./logs/log",$str.PHP_EOL, FILE_APPEND);      
					//file_put_contents('./logs/goods_id.txt', $val['id'].',', FILE_APPEND | LOCK_EX);
					Db::name('goods_list')->insert([
						'cate_id' => $cate_id,
						'goods_id' => $val['id'],
						'create_time' => date('Y-m-d H:i:s',time())
					]);
				}
			}
		} 
		$this->success('获取成功');
		//halt($goods_ids);
    }
	
	public function get_goods_detail(){
		
		$goods_ids_arr = Db::name('goods_list')->order('id asc')->limit(300)->select();
		foreach($goods_ids_arr as $val){
			$is_exit = Db::name('goods')->where('sdzc_old_id',$val['goods_id'])->find();
			if($val['goods_id'] && empty($is_exit)){
				$url = 'http://ggzyjyzx.shandong.gov.cn/wssc/goods/'.$val['goods_id'];
				$res = $this->get_url($url);
				$data = json_decode($res,true);
				if($data['status'] == 'error'){
					Db::name('goods_list')->where('goods_id',$val['goods_id'])->delete();
					continue;
				}
				$UploadQiniu = new UploadQiniuModel();
				if(!empty($data['pics'])){
					$pic_arr = $data['pics'];
					$photo = [];
					foreach($pic_arr as $key=>$v){
						if($key <3){
							$back_img = $UploadQiniu->upload_cg_img($v['source']);
							if($back_img){
								$photo[$key]['url'] = $UploadQiniu->upload_cg_img($v['source']);
							}else{
								$photo[$key]['url'] = $v['source'];
							}
							$photo[$key]['name'] = '';
						}
					}
					$more['photos'] = $photo;
				}else{
					$more = [];
				}
				$thumbnail = $UploadQiniu->upload_cg_img($data['coverUrl']);
				if($thumbnail == false){
					$thumbnail = $data['coverUrl'];
				}
				$content = $UploadQiniu->get_content_img_url($data['detail']);
				if(!empty($data['energySaveCertAnnex'])){
					$jnhb_img = $UploadQiniu->upload_cg_img($data['energySaveCertAnnex']);
					if($jnhb_img == false){
						$data['energySaveCertAnnex'] = $data['energySaveCertAnnex'];
					}else{
						$data['energySaveCertAnnex'] = $jnhb_img;
					}
				}
				$cate_id = Db::name('goods_category')->where('platformCatalogId',$data['catalogId'])->value('id');
				$brand_id = Db::name('goods_brand')->where('old_brand_id',$data['brandId'])->value('id');
				$post_data = [
					'cate_id' => empty($cate_id)?0:$cate_id,
					'brand_id' => empty($brand_id)?0:$brand_id,
					'brand_name' => $data['brandName'],
					'ppmc'	=> $data['brandName'],
					'mode' => $data['model'],
					'param'	=> !empty($data['param']) ? $data['param']:'',
					'post_title' => $data['name'],
					'yg_sku' => 'mjyx_'.cmf_get_order_sn(),
					'stock'	=> 1000,
					'price' => $data['marketPrice'],
					'cg_price' => $data['price'],
					'post_content' => $content,
					'thumbnail' => $thumbnail,
					'more' => json_encode($more),
					'create_time' => time(),
					'unit'	=> !empty($data['unit']) ? $data['unit']:'无',
					'area' => !empty($data['productArea'])?$data['productArea']:'无',
					'upc' => !empty($data['upc'])?$data['upc']:'',
					'service' => !empty($data['afterSaleService'])?$data['afterSaleService']:'',
					'save_energy_cert_no' => !empty($data['energySaveCertNo']) ? $data['energySaveCertNo']:'',
					'save_energy_cert_image' => !empty($data['energySaveCertAnnex']) ? $data['energySaveCertAnnex']:'',
					'save_energy_cert_indate' => !empty($data['energySaveCertValidity']) ? $data['energySaveCertValidity']:'',
					'sdzc_old_id' => $val['goods_id']
				];
				Db::name('goods')->insert($post_data);
				Db::name('goods_list')->where('goods_id',$val['goods_id'])->delete();
			}elseif($is_exit){
				Db::name('goods_list')->where('goods_id',$val['goods_id'])->delete();
			}
		}
		$this->success('执行成功');
	}
	
	public function get_single_goods_detail(){
		
		$val = 989407;
		$url = 'http://ggzyjyzx.shandong.gov.cn/wssc/goods/'.$val;
		$res = $this->get_url($url);
		$data = json_decode($res,true);
		$UploadQiniu = new UploadQiniuModel();
		$pic_arr = $data['pics'];
		if(!empty($pic_arr)){
			$photo = [];
			foreach($pic_arr as $key=>$v){
				$photo[$key]['url'] = $UploadQiniu->upload_cg_img($v['source']);
				$photo[$key]['name'] = '';
			}
			$more['photos'] = $photo;
		}else{
			$more = [];
		}
		$thumbnail = $UploadQiniu->upload_cg_img($data['coverUrl']);
		$content = $UploadQiniu->get_content_img_url($data['detail']);
		if(!empty($data['energySaveCertAnnex'])){
			$data['energySaveCertAnnex'] = $UploadQiniu->upload_cg_img($data['energySaveCertAnnex']);
		}
		$cate_id = Db::name('goods_category')->where('platformCatalogId',$data['catalogId'])->value('id');
		$brand_id = Db::name('goods_brand')->where('old_brand_id',$data['brandId'])->value('id');
		$post_data = [
			'cate_id' => empty($cate_id)?0:$cate_id,
			'brand_id' => empty($brand_id)?0:$brand_id,
			'brand_name' => $data['brandName'],
			'ppmc'	=> $data['brandName'],
			'mode' => $data['model'],
			'param'	=> !empty($data['param']) ? $data['param']:'',
			'post_title' => $data['name'],
			'yg_sku' => 'mjyx_'.cmf_get_order_sn(),
			'stock'	=> 1000,
			'price' => $data['marketPrice'],
			'cg_price' => $data['price'],
			'post_content' => $content,
			'thumbnail' => $thumbnail,
			'more' => json_encode($more),
			'create_time' => time(),
			'unit'	=> !empty($data['unit']) ? $data['unit']:'无',
			'area' => !empty($data['productArea'])?$data['productArea']:'无',
			'upc' => !empty($data['upc'])?$data['upc']:'',
			'service' => !empty($data['afterSaleService'])?$data['afterSaleService']:'',
			'save_energy_cert_no' => !empty($data['energySaveCertNo']) ? $data['energySaveCertNo']:'',
			'save_energy_cert_image' => !empty($data['energySaveCertAnnex']) ? $data['energySaveCertAnnex']:'',
			'save_energy_cert_indate' => !empty($data['energySaveCertValidity']) ? $data['energySaveCertValidity']:'',
			'sdzc_old_id' => $val
		];
		halt($post_data);
		Db::name('goods')->insert($post_data);
	}
	
	
	public function set_stock()
	{	
		$Redis = new Redis();
		$Redis->rPush('goods_stock',1);
		
		$user_id = $Redis->lPop('goods_stock');
		dump($user_id);
	}
	

	function get_child($data){
		foreach($data as $val){
			$arr['name'] = $val['name'];
			$arr['parent_id'] = 0;
			$arr['platformCatalogId'] = 0;
			$first_id = Db::name('goods_category')->insertGetId($arr);
			if(!empty($val['children'])){
				foreach($val['children'] as $v){
					$ar['name'] = $v['name'];
					$ar['parent_id'] = $first_id;
					$ar['platformCatalogId'] = 0;
					$sec_id = Db::name('goods_category')->insertGetId($ar);
					if(!empty($v['children'])){
						foreach($v['children'] as $vv){
							$a['name'] = $vv['name'];
							$a['parent_id'] = $sec_id;
							$a['platformCatalogId'] = $vv['platformCatalogId'];
							Db::name('goods_category')->insertGetId($a);
						}
					}
				}
			}
		} 
		return true;
	}
	
	
	function get_url($url) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_HTTPGET, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //TRUE 将curl_exec()获取的信息以字符串返回，而不是直接输出。
		$header = [
		'Content-Type: application/json;charset=UTF-8',
		'siteCode: sdszfcg'
		]; //设置一个你的浏览器agent的header
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_HEADER, 0); //返回response头部信息
		curl_setopt($ch, CURLINFO_HEADER_OUT, true); //TRUE 时追踪句柄的请求字符串，从 PHP 5.1.3 开始可用。这个很关键，就是允许你查看请求header
		curl_setopt($ch, CURLOPT_URL, $url);
		$result = curl_exec($ch);
		curl_close($ch);
		return $result;
	}
	
}
